import { Injectable } from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router} from '@angular/router';
import { Observable } from 'rxjs';
import {FbService} from '../services/fb.service';
import {map} from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(
    public fbService: FbService,
    public router: Router
  ) {

  }

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {

    return this.fbService.isAuth().pipe(
      map(
        auth => {
          if (!auth) {
            return true;
          } else {
            this.router.navigate(['/']);
            return false;
          }
        }
      )
    );

  }

}
